package com.sanctity.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/***
 * @belongsProject spring-cloud
 * @description <设置RabbitTemplate的回执机制的回调函数>
 * @author Sanct
 * @version 1.0.0
 * @create 2024/1/25 17:43
 **/
@Configuration
@Slf4j
public class CommonConfig implements ApplicationContextAware {
    // 实现ApplicationContextAware接口，当spring容器创建完成Bean工厂之后即可通知该类
    // 从而获取到RabbitTemplate的注册对象，设置其回执机制的回调函数
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplateBean = applicationContext.getBean(RabbitTemplate.class);
        rabbitTemplateBean.setReturnCallback((message,replyCode,replyText,exchange,routingKey) -> {
            // 记录日志
            log.error("消息转发到队列失败，响应码：{}，失败原因：{}，交换机：{}，路由key：{}，消息：{}",
                    replyCode,replyText,exchange,routingKey,message.toString());
            // 如果有需要，重发消息
        });
    }
}
